import {getToken, setToken, removeToken} from "@/utils/auth";
import { login, getInfo, logout } from "@/api/login";


const user = {
    state: {
        token: getToken(),
        id: '',
        userName: '',
        email: '',
        wallet: 0,
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_ID: (state, id) => {
          state.id = id
        },
        SET_NAME: (state, userName) => {
            state.userName = userName
        },
        SET_EMAIL: (state, email) => {
            state.email = email
        },
        SET_WALLET: (state, wallet) => {
            state.wallet = wallet
        },
    },

    actions: {
        // 登录
        Login({commit}, loginForm) {
            const username = loginForm.email.trim()
            const password = loginForm.password
            const uuid = loginForm.uuid
            return new Promise((resolve, reject) => {
                login(username, password, uuid).then(response => {
                    setToken(response.token)
                    commit('SET_TOKEN', response.token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getInfo().then((response) => {
                    const user = response.user
                    commit('SET_ID', user.id)
                    commit('SET_NAME', user.userName)
                    commit('SET_EMAIL', user.email)
                    commit('SET_WALLET', user.wallet)
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 退出按钮
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_EMAIL', '')
                    removeToken()
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 前端 登出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                commit('SET_EMAIL', '')
                removeToken()
                resolve()
            })
        }

    }


}

export default user
